import { throttle } from "@/utils";
import { cacheModel } from "./useListCore.type";
interface cacheStorageModel extends cacheModel{
    key: string
 }
interface cacheDataModel{ [key: string] : cacheStorageModel }
export class DataStorageExtension {
    // 这是为了轮换索引
    keyUnitMap = ['A', 'B', 'C'];
    // 缓存数据 根据key:value 存储
    cacheData: cacheDataModel = {};
    // 维护当前 已经存储的key值，用于数据的删除
    cacheKeyQue = '';
    // 维护当前 已经存储的数据长度
    cacheLength = 0;
    // 当前最新的key
    currentKey = "";
    // 当前溢出的key
    currentRemoveKey = "";
    // 当前存储的数据量上限
    // limitValue = 20_000;
    limitValue = 20_0;
    // 删除数据的节流阀值
    throttleDelay = 300;
    // 私有的自增key
    private key = 0;
    // 私有的自增前缀索引
    private keyUnitIndex = 0;
    // 私有的自增前缀值
    private keyUnit = this.keyUnitMap[0];
    // constructor() {}
    // 根据自增规则生成唯一key值
    getKey() {
        this.key++;
        if (this.key > this.limitValue) {
            this.key = 0;
            this.keyUnitIndex++;
            if (this.keyUnitIndex >= this.keyUnitMap.length - 1) {
                this.keyUnitIndex = 0;
            }
            this.keyUnit = this.keyUnitMap[this.keyUnitIndex];
        }
        return this.keyUnit + this.key;
    }

    // 向缓存里面增加数据
    add(item: cacheModel) {
        const _key = this.getKey();
        item.key = _key;
        this.currentKey = _key;
        this.cacheKeyQue += ('|' + _key);
        this.cacheData[_key] = item as cacheStorageModel;
        this.cacheLength++;
        if (this.cacheLength > this.limitValue) {
            this.currentRemoveKey = _key;
            this.throttleRemove();
        }
    }

    throttleRemove = throttle(() => {
        const _key = this.currentRemoveKey;
        const index = this.cacheKeyQue.indexOf(_key);
        console.log("123", index, _key, this.cacheKeyQue);
        if (index !== -1) {
            const removeKey = this.cacheKeyQue.substring(0, index + _key.length);
            this.remove(removeKey.split('|'));
        }
    }, this.throttleDelay);

    // 中转站-删除缓存数据
    remove(key: string | string[]) {
        if (!Array.isArray(key)) {
            this.removeCache(key);
        } else {
            for (let i = 0; i < key.length; i++) {
                this.removeCache(key[i]);
            }
        }
    }

    // 删除缓存数据
    removeCache(key: string) {
        if (this.cacheData[key]) {
            delete this.cacheData[key];
            this.cacheKeyQue.replace('|' + key, '');
            this.cacheLength--;
        }
    }
}
